<script setup>
import { storeToRefs } from 'pinia'
import { useAppStore } from '../stores/appStore'
import WorkflowNode from './WorkflowNode.vue'
import { computed, ref, nextTick, watch, onMounted } from 'vue'
import { Plus, Delete, VideoPlay, Edit, CopyDocument, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import NodeLibrary from './NodeLibrary.vue'
import NodeDialog from './NodeDialog.vue'
import { v4 as uuidv4 } from 'uuid'

const store = useAppStore()
const { applications, activeAppId } = storeToRefs(store)
const activeApp = computed(() => store.activeApp)
const activeAppName = ref(activeApp.value?.name || '')

const nodeRefs = ref([])
const isEditing = ref({})
const isEditingTitle = ref(false)
const isNodeLibraryVisible = ref(false)
const isNodeDialogVisible = ref(false)
const nodeDialog = ref(null)
const isTemplateSelectVisible = ref(false)
const currentNodeId = ref(null)
const currentWorkflowId = ref(null)

// 添加 refs
const appTitleInput = ref(null)
const workflowTitleInputs = ref({})
const workflowContainer = ref(null)

// 监听工作流变化，自动滚动到最右侧
watch(() => activeApp.value?.workflows?.length, (newLength, oldLength) => {
  if (newLength > oldLength) {
    nextTick(() => {
      scrollToEnd()
    })
  }
}, { immediate: true })

// 滚动到最右侧的方法
const scrollToEnd = () => {
  if (workflowContainer.value) {
    nextTick(() => {
      workflowContainer.value.scrollLeft = workflowContainer.value.scrollWidth
    })
  }
}

// 在组件挂载后也滚动到最右侧
onMounted(() => {
  nextTick(() => {
    scrollToEnd()
  })
})

// 清空所有节点
const clearAllNodesIO = async () => {
  try {
    await store.clearAllNodes()
    ElMessage.success('已清空所有节点')
  } catch (error) {
    console.error('清空节点失败:', error)
    ElMessage.error('清空失败')
  }
}

// 清空当前工作流的节点
const clearWorkflowIO = async (workflow) => {
  try {
    await store.clearWorkflowNodes(workflow.id)
    ElMessage.success('已清空当前工作流的节点')
  } catch (error) {
    console.error('清空工作流节点失败:', error)
    ElMessage.error('清空失败')
  }
}

// 执行整个工作流
const executeWorkflow = async (workflow) => {
  try {
    await store.executeWorkflow(workflow.id)
    ElMessage.success('工作流执行完成')
  } catch (error) {
    console.error('工作流执行失败:', error)
    ElMessage.error(`执行失败: ${error.message}`)
  }
}

// 更新工作流名称
const updateWorkflowName = async (workflowId, newName) => {
  await store.updateWorkflowName(workflowId, newName)
}

// 处理删除工作流
const handleDeleteWorkflow = async (workflowId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个工作流吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await store.deleteWorkflow(workflowId)
    ElMessage.success('工作流已删除')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理删除应用
const handleDeleteApplication = async (appId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个应用吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await store.deleteApplication(appId)
    ElMessage.success('应用已删除')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 更新应用名称
const updateApplicationName = async (workflowId, newName) => {
  await store.updateApplicationName(workflowId, newName)
}

// 新增节点
const addNode = (workFlow, node, nodeIndex) => {
  nodeDialog.value.openDialog('add', workFlow, node, nodeIndex)
}
const addTemplateNode = () => {
  nodeDialog.value.openDialog('addToTemplate')
}
const EditNode = (workFlow, node, nodeIndex) => {
  nodeDialog.value.openDialog('edit', workFlow, node, nodeIndex)
}
const workflow = (workFlow) => {
  nodeDialog.value.openDialog('edit', workFlow)
}

const showNodeLibrary = () => {
  isNodeLibraryVisible.value = true
}

const editTemplateNode = (template) => {
  nodeDialog.value.openDialog('edit', null, template);
};

// 处理从节点库导入的点击事件
const handleImportFromLibrary = (nodeId, workflowId) => {
  currentNodeId.value = nodeId;
  currentWorkflowId.value = workflowId;
  isTemplateSelectVisible.value = true;
};

// 修改模板选择处理方法
const handleTemplateSelect = async (templates) => {
  if (!currentWorkflowId.value) return;

  try {
    const workflow = store.getWorkflowById(currentWorkflowId.value);
    if (!workflow) throw new Error('找不到工作流');

    // 处理多个模板
    for (const template of templates) {
      const newNode = {
        ...template,
        id: uuidv4(),
        status: '未执行',
        input: '',
        output: ''
      };

      if (currentNodeId.value) {
        // 在指定节点后插入
        await store.insertNodeAfter(currentWorkflowId.value, currentNodeId.value, newNode);
        currentNodeId.value = newNode.id; // 更新当前节点ID,使下一个节点插入到新节点后面
      } else {
        // 添加到工作流末尾
        await store.addNode(workflow, newNode);
      }
    }
    
    ElMessage.success(`成功导入 ${templates.length} 个节点`);
  } catch (error) {
    console.error('导入节点失败:', error);
    ElMessage.error('导入失败');
  } finally {
    isTemplateSelectVisible.value = false;
    currentNodeId.value = null;
    currentWorkflowId.value = null;
  }
};

// 修改编辑标题的方法
const startEditingTitle = async () => {
  isEditingTitle.value = true
  await nextTick()
  appTitleInput.value.focus()
}

// 修改编辑工作流标题的方法
const startEditingWorkflow = async (workflowId) => {
  isEditing.value[workflowId] = true
  await nextTick()
  workflowTitleInputs.value[workflowId]?.focus()
}

// 复制工作流
const handleCopyWorkflow = async (workflow) => {
  try {
    const workflowCopy = JSON.parse(JSON.stringify(workflow));
    workflowCopy.id = uuidv4();
    workflowCopy.name = `${workflow.name} 副本`;
    // 为工作流中的所有节点生成新的ID
    workflowCopy.nodes = workflowCopy.nodes.map(node => ({
      ...node,
      id: uuidv4(),
      status: '未执行',
      input: '',
      output: ''
    }));

    await store.addWorkflow(workflowCopy);
    ElMessage.success('工作流复制成功');
  } catch (error) {
    console.error('复制工作流失败:', error);
    ElMessage.error('复制失败');
  }
};

// 在 script setup 中添加新方法
const handleImportToWorkflow = (workflowId) => {
  currentWorkflowId.value = workflowId;
  isTemplateSelectVisible.value = true;
  currentNodeId.value = null; // 清空节点ID表示添加到末尾
};
</script>

<template>
  <div class="workspace">
    <header>
      <div class="workflow-title flex items-center justify-between mb-4">
        <span
          v-if="!isEditingTitle"
          class="text-xl font-bold cursor-pointer"
          @click="startEditingTitle"
        >
          {{ activeAppName }}
        </span>
        <el-input
          v-if="isEditingTitle"
          v-model="activeAppName"
          ref="appTitleInput"
          @blur="updateApplicationName(activeApp.id, activeAppName); isEditingTitle = false"
          @keyup.enter="updateApplicationName(activeApp.id, activeAppName); isEditingTitle = false"
          placeholder="请输入应用名称"
          style="width: 200px;"
        />
      </div>
    </header>
    <div class="workflow-controls">
      <el-button
        type="primary"
        @click="store.addWorkflow()"
      >
        <el-icon><Plus /></el-icon>
        添加工作流
      </el-button>
      <el-button
        type="warning"
        @click="clearAllNodesIO"
      >
        <el-icon><Delete /></el-icon>
        清空所有节点
      </el-button>
      <el-button
        type="danger"
        @click="handleDeleteApplication(activeAppId)"
      >
        <el-icon><Delete /></el-icon>
        删除应用
      </el-button>
      <el-button
        type="default"
        @click="showNodeLibrary"
      >
        节点库
      </el-button>
    </div>

    <div class="workflow-container" ref="workflowContainer">
      <div
        v-for="(workflow, workflowIndex) in store.activeApp?.workflows"
        :key="workflow.id"
        class="workflow-column"
      >
        <div class="workflow-header">
          <span
            v-if="!isEditing[workflow.id]"
            class="cursor-pointer"
            @click="startEditingWorkflow(workflow.id)"
          >
            {{ workflow.name }}
          </span>
          <el-input
            v-if="isEditing[workflow.id]"
            v-model="workflow.name"
            :ref="el => workflowTitleInputs[workflow.id] = el"
            @blur="updateWorkflowName(workflow.id, workflow.name); isEditing[workflow.id] = false"
            @keyup.enter="updateWorkflowName(workflow.id, workflow.name); isEditing[workflow.id] = false"
            placeholder="请输入工作流名称"
            size="small"
          />
          <div class="workflow-header-actions">
            <el-button
              v-if="!isEditing[workflow.id]"
              type="primary"
              link
              @click="handleCopyWorkflow(workflow)"
            >
              <el-icon><CopyDocument /></el-icon>
            </el-button>
            <el-button
              v-if="!isEditing[workflow.id]"
              type="primary"
              link
              @click="startEditingWorkflow(workflow.id)"
            >
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDeleteWorkflow(workflow.id)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="workflow-buttons">
          <el-button
            type="primary"
            @click="addNode(workflow)"
          >
            <el-icon><Plus /></el-icon>
            添加节点
          </el-button>
          <el-button
            type="primary"
            @click="handleImportToWorkflow(workflow.id)"
          >
            <el-icon><Download /></el-icon>
            导入节点
          </el-button>
          <el-button
            type="warning"
            @click="clearWorkflowIO(workflow)"
          >
            <el-icon><Delete /></el-icon>
            清空节点
          </el-button>
          <el-button
            type="success"
            @click="executeWorkflow(workflow)"
          >
            <el-icon><VideoPlay /></el-icon>
            开始执行
          </el-button>
        </div>

        <div class="nodes-wrapper">
          <WorkflowNode
            v-for="(node, nodeIndex) in workflow.nodes"
            :key="node.id"
            :node="node"
            :nodeIndex="nodeIndex"
            :workflowId="workflow.id"
            :workflow="workflow"
            ref="nodeRefs"
            @addNode="addNode"
            @updateNode="EditNode"
            @importFromLibrary="(nodeId) => handleImportFromLibrary(nodeId, workflow.id)"
          />
        </div>
      </div>
    </div>

    <el-dialog
      v-model="isNodeLibraryVisible"
      title="节点库"
      width="80%" 
      top="5vh"
      :destroy-on-close="false"
      class="node-library-dialog"
    >
      <NodeLibrary
        @addTemplateNode="addTemplateNode"
        @editTemplate="editTemplateNode"
        @close="isNodeLibraryVisible = false"
      />
    </el-dialog>
    <el-dialog
      v-model="isTemplateSelectVisible"
      title="选择模板节点"
      width="80%"
      top="5vh"
      :destroy-on-close="false"
      class="node-library-dialog"
    >
      <NodeLibrary
        :select-mode="true"
        @select-templates="handleTemplateSelect"
        @close="isTemplateSelectVisible = false"
      />
    </el-dialog>
    <NodeDialog ref="nodeDialog" />

  </div>
</template>

<style scoped>
.workflow-controls {
  padding: 12px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap; /* 允许按钮在小屏幕上换行 */
}

.workflow-container {
  display: flex;
  padding: 20px;
  gap: 24px;
  height: calc(100vh - 180px);
  overflow-x: auto;
  /* 增强横向滚动体验 */
  scroll-behavior: smooth; /* 平滑滚动 */
  -webkit-overflow-scrolling: touch; /* 在iOS上提供更好的滚动体验 */
  scrollbar-width: thin; /* Firefox的滚动条样式 */
  /* 添加阴影效果 */
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background-color: #f9fafc;
  margin: 0 12px 12px;
}

/* 自定义横向滚动条样式 */
.workflow-container::-webkit-scrollbar {
  height: 8px; /* 横向滚动条高度 */
}

.workflow-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.workflow-container::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 4px;
}

.workflow-container::-webkit-scrollbar-thumb:hover {
  background: #999;
}

.workflow-column {
  min-width: 300px;
  background: #ffffff; /* 修改为纯白色背景 */
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  height: fit-content;
  max-height: 100%;
  /* 确保工作流列不会被压缩 */
  flex-shrink: 0;
  /* 添加边框 */
  border: 1px solid #ebeef5;
  /* 添加过渡效果 */
  transition: transform 0.2s, box-shadow 0.2s;
}

/* 鼠标悬停效果 */
.workflow-column:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.12);
}

.workflow-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: #f5f7fa; /* 修改标题栏背景色 */
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.workflow-header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.workflow-header span::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 14px;
  background: #67c23a;
  border-radius: 2px;
}

.workflow-buttons {
  display: flex;
  gap: 10px;
  padding-bottom: 10px;
  flex-wrap: wrap; /* 允许按钮在小屏幕上换行 */
}

/* 调整按钮大小，使其更紧凑 */
.workflow-buttons :deep(.el-button) {
  padding: 8px 12px;
}

/* 调整图标大小 */
.workflow-buttons :deep(.el-icon) {
  font-size: 14px;
}

.nodes-wrapper {
  flex: 1;
  overflow-y: auto;
  padding-right: 8px; /* 为滚动条预留空间 */
  margin-right: -8px; /* 补偿padding-right */
  background-color: #fafafa; /* 节点区域背景色 */
  border-radius: 6px;
  padding: 10px;
}

/* 自定义滚动条样式 */
.nodes-wrapper::-webkit-scrollbar {
  width: 6px;
}

.nodes-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.nodes-wrapper::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.nodes-wrapper::-webkit-scrollbar-thumb:hover {
  background: #999;
}

.workflow-title {
  padding: 16px 20px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  margin-bottom: 20px;
}

.workflow-title span {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  position: relative;
  padding-left: 16px;
}

.workflow-title span::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: #409eff;
  border-radius: 2px;
}

/* 添加节点库弹窗样式 */
:deep(.node-library-dialog .el-dialog__body) {
  padding: 0;
  max-height: 80vh;
  overflow-y: auto;
}

:deep(.node-library-dialog .el-dialog__header) {
  padding: 16px 20px;
  margin-right: 0;
  border-bottom: 1px solid #ebeef5;
}

:deep(.node-library-dialog .el-dialog__headerbtn) {
  top: 16px;
}
</style>
